<?php

class UserController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/main';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    // public function accessRules() {
    //     return array(
    //     );
    // }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $this->menu = Menu::model()->findAll();
        $model = new User;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            // print_r($_POST);die();
            $birthday = $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'];
            unset($_POST['User']['rules']);
            unset($_POST['year']);
            unset($_POST['month']);
            unset($_POST['day']);
            $pass = md5($_POST['password']) . md5('xachdo');
            // print_r($birthday);die();
            $model->attributes = $_POST['User'];
            $model->birthday = date("Y-m-d",strtotime($birthday));
            $model->password = $pass;
            $model->roles_id = 0;

            if ($model->attributes['avatar_url'] === null) {
                $model->avatar = "default";

                if ($model->gender == 1) {
                    $model->avatar_url = "male.jpg";
                } else {
                    $model->avatar_url = "female.png";
                }
            }
            
            if ($model->save())
            {
                // var_dump($model->save());exit();
                $login = new LoginForm;
                $login->attributes = $_POST['User'];
                $login->password = $_POST['password'];
                
                if($login->login())
                {
                    $url = Yii::app()->createAbsoluteUrl('trang-chu');
                    $this->redirect($url,true);
                }
            }
            else{
                $model->insert();
                $login = new LoginForm;
                $login->attributes = $_POST['User'];
                $login->password = $_POST['password'];
                if($login->login())
                {
                    $url = Yii::app()->createAbsoluteUrl('trang-chu');
                    $this->redirect($url,true);
                }
            }
        }
        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {

        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            // print_r($_POST['User']);exit();
            $birthday = $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'];

            unset($_POST['year']);
            unset($_POST['month']);
            unset($_POST['day']);

            $model->attributes = $_POST['User'];
            $model->birthday = $birthday;

            if ($model->attributes['avatar_url'] == null) {
                $model->avatar = "default";

                if ($model->gender == 1) {
                    $model->avatar_url = "male.png";
                } else {
                    $model->avatar_url = "female.png";
                }
            } else {
                $imageUploadFile = CUploadedFile::getInstance($model, 'avatar_url');

                if ($imageUploadFile !== null) { // only do if file is really uploaded
                    // delete old avatar
                    $old_avatar = $model->avatar_url;
                    // check if old_avatar exists
                    if(file_exists(Yii::app()->basePath . "/../images/avatar/" . $old_avatar)){
                        unlink(Yii::app()->basePath . "/../images/avatar/" . $old_avatar);    
                    }
                    

                    $model->avatar = $imageUploadFile->name;
                    $imageFileName = date('YmdHis') . $model->username;
                    $model->avatar_url = $imageFileName . "." . $imageUploadFile->extensionName;
                    $imageUploadFile->saveAs(Yii::app()->basePath . "/../images/avatar/" . $imageFileName . "." . $imageUploadFile->extensionName);
                }
            }

            if ($model->save()) {
                $this->redirect(Yii::app()->createAbsoluteUrl('chinh-sua-thong-tin'));
                break;
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionCheckAvailable()
    {
        if(isset($_POST['User']['username'])){
            // print_r($_POST);exit();
           $user =  User::model()->findAllByAttributes(array('username' => $_POST['User']['username']));
           // print_r($user);exit();
           if($user == null){
                $msg = "true";
                // json_encode($msg);
                echo $msg;
           }
           else
           {
                $msg = "false";
                echo $msg;
           }
        }
        if(isset($_POST['User']['email'])){
            $email = User::model()->findAllByAttributes(array('email' => $_POST['User']['email']));
            if($email == null){
                $msg = "true";
                echo $msg;
            }else{
                $msg = "false";
                echo $msg;
            }
        }

    }
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        //get current user throught the session
        $user = User::model()->findByAttributes(array('username'=>Yii::app()->user->id));
        //get user infomation from database
        $u_info = User::model()->findByPk($user->id);
        $u_info['birthday'] = explode('-', date("d-m-Y",strtotime($u_info['birthday'])));
        // print_r($user);die();
        $this->render('index',array('user' => $u_info));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new User('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['User']))
            $model->attributes = $_GET['User'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return User the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param User $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
